# -*- coding=utf-8
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
import sys
import os
import logging
from django.conf import settings
from qcloud_cos.cos_exception import CosServiceError


def create_cos(bucket, region='ap-chengdu'):
    """
    创建桶
    :param region: 区域
    :param bucket: 桶名称
    :return:
    """

    token = None  # 如果使用永久密钥不需要填入 token，如果使用临时密钥需要填入，临时密钥生成和使用指引参见 https://cloud.tencent.com/document/product/436/14048
    scheme = 'https'  # 指定使用 http/https 协议来访问 COS，默认为 https，可不填

    config = CosConfig(Region=region, SecretId=settings.TENCENT_COS_ID, SecretKey=settings.TENCENT_COS_KEY, Token=token,
                       Scheme=scheme)
    client = CosS3Client(config)

    response = client.create_bucket(
        Bucket=bucket,
        ACL='public-read',
    )
    cors_config = {
        'CORSRule': [
            {
                'AllowedOrigin': '*',
                'AllowedMethod': ['GET', 'PUT', 'HEAD', 'POST', 'DELETE'],
                'AllowedHeader': "*",
                'ExposeHeader': "*",
                'MaxAgeSeconds': 500
            }
        ]
    }
    client.put_bucket_cors(
        Bucket=bucket,
        CORSConfiguration=cors_config
    )


def upload_file(bucket, region, file_obj, key):
    scheme = 'https'  # 指定使用 http/https 协议来访问 COS，默认为 https，可不填

    config = CosConfig(Region=region, SecretId=settings.TENCENT_COS_ID, SecretKey=settings.TENCENT_COS_KEY,
                       Scheme=scheme)
    client = CosS3Client(config)

    response = client.upload_file_from_buffer(
        Bucket=bucket,
        Key=key,
        Body=file_obj,
    )

    # 返回图片路径 https://test-1360779007.cos.ap-chengdu.myqcloud.com/test.jpg
    return 'https://{}.cos.{}.myqcloud.com/{}'.format(bucket, region, key)


def delete_file(region, bucket, key):
    """
    删除文件
    :param region: 地区
    :param bucket: 桶名称
    :param key: 文件名称
    :return:
    """
    scheme = 'https'  # 指定使用 http/https 协议来访问 COS，默认为 https，可不填

    config = CosConfig(Region=region, SecretId=settings.TENCENT_COS_ID, SecretKey=settings.TENCENT_COS_KEY,
                       Scheme=scheme)
    client = CosS3Client(config)
    client.delete_object(
        Bucket=bucket,
        Key=key
    )


def delete_file_list(region, bucket, key_list):
    """
    删除文件
    :param region: 地区
    :param bucket: 桶名称
    :param key_list: 文件名称列表
    :return:
    """
    scheme = 'https'  # 指定使用 http/https 协议来访问 COS，默认为 https，可不填

    config = CosConfig(Region=region, SecretId=settings.TENCENT_COS_ID, SecretKey=settings.TENCENT_COS_KEY,
                       Scheme=scheme)
    client = CosS3Client(config)
    objects = {
        "Quiet": "true",
        "Object": key_list
    }
    client.delete_objects(
        Bucket=bucket,
        Delete=objects
    )


def check_file(region, bucket, key):
    """
    检查文件是否存在于cos
    :param region:
    :param bucket:
    :param key:
    :return:
    """
    config = CosConfig(Region=region, SecretId=settings.TENCENT_COS_ID, SecretKey=settings.TENCENT_COS_KEY,
                       )
    client = CosS3Client(config)
    data = client.head_object(
        Bucket=bucket,
        Key=key
    )
    return data


def credential(bucket, region):
    """
    获取临时凭证
    :param request:
    :param bucket:  桶名称
    :param region: 区域
    :return:
    """
    from sts.sts import Sts
    config = {
        # 临时密钥有效时长，单位是秒（30分钟=1800秒）
        'duration_seconds': 1800,
        # 固定密钥 id
        'secret_id': settings.TENCENT_COS_ID,
        # 固定密钥 key
        'secret_key': settings.TENCENT_COS_KEY,
        # 换成你的 bucket
        'bucket': bucket,
        # 换成 bucket 所在地区
        'region': region,
        # 这里改成允许的路径前缀，可以根据自己网站的用户登录态判断允许上传的具体路径
        # 例子： a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)
        'allow_prefix': '*',
        # 密钥的权限列表。简单上传和分片需要以下的权限，其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
        'allow_actions': [
            # ’name/cos:PutObject‘
            # 'name/cos:PostObject',
            # 'name/cos:DeleteObject',
            # "name/cos:UploadPart",
            # "name/cos:UploadPartCopy",
            # "name/cos:CompleteMultipartUpload",
            # "name/cos:AbortMultipartUpload",
            "*",
        ],

    }

    sts = Sts(config)
    result_dict = sts.get_credential()
    return result_dict


def delete_bucket(bucket, region):
    """删除桶"""
    config = CosConfig(Region=region, SecretId=settings.TENCENT_COS_ID, SecretKey=settings.TENCENT_COS_KEY)
    client = CosS3Client(config)
    # 1.删除桶里面所有文件
    # 2.删除所有碎片文件
    file_obj = client.list_buckets(bucket)
    try:
        # 找到桶中所有文件
        while True:
            file_obj = client.list_objects(bucket)
            contents = file_obj.get('Contents')
            if not contents:
                break

            # 批量删除
            objects = {
                'Quiet': 'true',
                "Object": [{'Key': item['Key']} for item in contents]
            }
            client.delete_objects(bucket, objects)

            if file_obj['IsTruncated'] == 'false':
                break

        # 找到碎片文件
        while True:
            part_uploads = client.list_multipart_uploads(bucket)
            uploads = part_uploads.get('Upload')
            if not uploads:
                break
            for item in uploads:
                client.abort_multipart_upload(bucket, item['Key'], item['UploadId'])

            if file_obj['IsTruncated'] == 'false':
                break

        client.delete_bucket(bucket)
    except CosServiceError as e:
        pass
